/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.bsc.relay.service;


import com.bsc.foundation.DSPropertyPlaceholderConfigurer;
import com.bsc.relay.server.command.concrete.RelayRegisterCommand;
import com.bsc.util.srping.SpringUtil;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.springframework.stereotype.Component;

/**
 *
 * @author penn
 */
@Component
public class ConnectSession {

    private DSPropertyPlaceholderConfigurer allProperties;
    private NioSocketConnector ioConnector;
    private static ConnectSession connectSession = null;
    public IoSession session;
    private ConnectFuture connectFuture;
    private long TimeOut;

    private ConnectSession() {
        ioConnector = (NioSocketConnector) SpringUtil.getInstance().getBean("ioConnector");
        TimeOut = ioConnector.getConnectTimeoutMillis();
        connectFuture = ioConnector.connect();      
        connectFuture.awaitUninterruptibly(TimeOut);
        session = connectFuture.getSession();
        register();
    }

    synchronized public static ConnectSession getIoConnector() {
        if (connectSession == null) {
            connectSession = new ConnectSession();
        }
        return connectSession;
    }
    
    private void register(){
        DSPropertyPlaceholderConfigurer allProperties = (DSPropertyPlaceholderConfigurer) SpringUtil.getInstance().getBean("allProperties");
        RelayRegisterCommand rrc = new RelayRegisterCommand();
        rrc.setRegisterName((String)allProperties.getProperty("Server.Name"));
        session.write(rrc);
    }

    public IoSession getSession() {
        if (this.session == null || !this.session.isConnected()) {
            connectFuture = ioConnector.connect();
            connectFuture.awaitUninterruptibly(TimeOut);
            session = connectFuture.getSession();
            register();
        }
        return session;
    }
}
